import React, { useState, useEffect, useRef } from "react";
import { AutoSizer, List } from "react-virtualized";
import MyNavBar from "../../components/MyNavBar";
import { Toast } from "antd-mobile";
import { getCity } from "../../utils/city";
import API from "../../utils/api";
import "./index.css";

// 索引（A、B等）的高度
const TITLE_HEIGHT = 36;
// 每个城市名称的高度
const NAME_HEIGHT = 50;
// 目前有房源的城市
// const HOUSE_CITIES = ['北京', '南京', '上海', '广州', '深圳'];

export default function CityList(props) {
  const [cityList, setcityList] = useState({});
  const [cityIndex, setcityIndex] = useState([]);
  const [activeIndex, setactiveIndex] = useState(0);
  const cityListComponent = useRef(null);
  // 获取城市列表数据
  useEffect(() => {
    // 城市数据格式化
    function formatCityData(list) {
      let cityList = {};
      let cityIndex = [];
      // 将城市列表list按照首字母进行分类
      list.forEach((item) => {
        let firstStr = item.short.substr(0, 1);
        if (cityList[firstStr]) {
          cityList[firstStr].push(item);
        } else {
          cityList[firstStr] = [item];
        }
      });
      // 获取城市列表首字母数组
      cityIndex = Object.keys(cityList).sort();
      return {
        cityList,
        cityIndex,
      };
    }
    const getCityList = async () => {
      Toast.loading("Loading...", 0, null, false);
      const res = await API.get("/area/city?level=1");
      Toast.hide();
      const { cityList, cityIndex } = formatCityData(res.data.body);

      // 获取热门城市,并添加至数据中
      const hotCities = await API.get("/area/hot");
      cityList["hot"] = hotCities.data.body;
      cityIndex.unshift("hot");

      // 获取当前定位城市
      const currentCity = getCity();
      cityList["#"] = [currentCity];
      cityIndex.unshift("#");
      setcityList(cityList);
      setcityIndex(cityIndex);
      cityListComponent.current.measureAllRows();
    };
    getCityList();
  }, []);

  // 封装处理字母索引的方法
  function formatCityIndex(letter) {
    switch (letter) {
      case "#":
        return "当前定位";
      case "hot":
        return "热门城市";
      default:
        return letter.toUpperCase();
    }
  }

  // List组件渲染每一行的方法：
  const rowRenderer = ({ key, index, style }) => {
    // 字母索引
    const letter = cityIndex[index];

    return (
      <div key={key} style={style} className="city">
        <div className="title">{formatCityIndex(letter)}</div>
        {
          // 渲染指定字母索引下的城市列表数据
          cityList[letter].map((item) => (
            <div
              className="name"
              key={item.value}
              onClick={() => changeCity(item)}
            >
              {item.label}
            </div>
          ))
        }
      </div>
    );
  };

  // 用于获取List 组件中渲染行的信息
  const rowsRendered = ({ startIndex }) => {
    // startIndex 当前城市列表顶部的索引号
    if (startIndex !== activeIndex) {
      setactiveIndex(startIndex);
    }
  };

  // 创建动态计算每一行高度的方法
  const getRowHeight = ({ index }) => {
    return TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT;
  };

  // 封装渲染右侧索引列表的方法
  const renderCityIndex = () => {
    // 获取到 cityIndex，并遍历其，实现渲染
    return cityIndex.map((item, index) => (
      <li
        className="city-index-item"
        key={item}
        onClick={() => {
          cityListComponent.current.scrollToRow(index);
        }}
      >
        <span className={activeIndex === index ? "index-active" : ""}>
          {item === "hot" ? "热" : item.toUpperCase()}
        </span>
      </li>
    ));
  };

  // 点击切换城市
  const changeCity = (city) => {
    const { label, value } = city;
    localStorage.setItem("zfy_city", JSON.stringify({ label, value }));
    props.history.goBack();
  };
  return (
    <div className="citylist">
      <MyNavBar>城市选择</MyNavBar>
      {/* 城市列表 */}
      <AutoSizer>
        {({ width, height }) => (
          <List
            ref={cityListComponent}
            width={width}
            height={height}
            rowCount={cityIndex.length}
            rowHeight={getRowHeight}
            rowRenderer={rowRenderer}
            onRowsRendered={rowsRendered}
            scrollToAlignment="start"
          />
        )}
      </AutoSizer>
      {/* 右侧索引列表 */}
      <ul className="city-index">{renderCityIndex()}</ul>
    </div>
  );
}
